<?php
require 'autoload.php';

session_start();
if (!session_is_registered('user')) exit();
$config = sqlite_open("config.db");
$gen = @sqlite_fetch_array(@sqlite_query($config, "SELECT * FROM general"));
$HTTP_REFERER = $_SERVER['HTTP_REFERER'];

$close = "<script id=\"clientEventHandlersJS\" language=\"javascript\">
          <!--
          function OnLoad()
          {
            window.close(\"do\");
          }
          -->
          </script>
          <body onload=\"OnLoad()\">
          ";


if ($_GET['what'] == "qs") {
  $id = $_GET['id'];
  $lib = $_GET['library'];
  $num = count($_SESSION['queue']);
  $_SESSION['queue'][$num] = $id;
  echo "<script language=\"JavaScript1.2\">
	queue.location.reload( true );
	</script>";

  echo $close;
  exit();
}

if (!session_is_registered('admin')) exit();

if ($_GET['what'] == "themes") {
  @sqlite_query($config, "DROP TABLE themes");
  sqlite_query($config, "CREATE TABLE themes ('id' VARCHAR(100), 'name' VARCHAR(100), 'image' VARCHAR(255), 'file' VARCHAR(255))");
  $d = opendir($gen['path']."\\themes");
  while ($theme = readdir($d)) {
    if (($theme != ".") && ($theme != "..")) {
      if (file_exists($gen['path']."\\themes\\$theme\\theme.plugin")) {
        $src = $gen['path']."\\themes\\$theme\\theme.plugin";
        $info = simplexml_load_file($gen['path']."\\themes\\$theme\\theme.plugin");
        $found = 1;
      }
      else {
        $th = opendir($gen['path']."\\themes\\$theme");
        while ($file = readdir($th)) {
          if (strtolower(strrchr($file, ".")) == ".plugin") {
            $src = $gen['path']."\\themes\\$theme\\$file";
            $info = simplexml_load_file($gen['path']."\\themes\\$theme\\$file");
            $found = 1;
          }
        }
      }
      if ($found == 1) {
        $name = addslashes($info->{'plugin-name'});
        $id = $info->{'plugin-id'};
        if (file_exists($gen['path']."\\themes\\$theme\\screenshot.jpg")) $image = $gen['path']."\\themes\\$theme\\screenshot.jpg";
        elseif (file_exists($gen['path']."\\themes\\$theme\\screenshot.png")) $image = $gen['path']."\\themes\\$theme\\screenshot.png";
        elseif (file_exists($gen['path']."\\themes\\$theme\\screenshot.gif")) $image = $gen['path']."\\themes\\$theme\\screenshot.gif";
        elseif (file_exists($gen['path']."\\themes\\$theme\\screenshot.bmp")) $image = $gen['path']."\\themes\\$theme\\screenshot.bmp";
        elseif (($ss = opendir($gen['path']."\\themes\\$theme\\screenshots")) != FALSE) {
          while ($f = readdir($ss)) {
            $ext = strtolower(strrchr($f, "."));
            if (($ext == ".jpg") || ($ext == ".jpeg") || ($ext == ".gif") || ($ext == ".png") || ($ext == ".bmp")) {
              $image = $gen['path']."\\themes\\$theme\\screenshots\\$f";
            }
          }
        }
        sqlite_query($config, "INSERT INTO themes (id, name, image, file) VALUES('$id',\"$name\",'$image','$src')");
      }
    }
    unset($id,$name,$image,$src,$found);
  }
  echo $i;
  header("Location: $HTTP_REFERER");
  exit();
}

if ($_GET['what'] == "theme") {
  if ($_GET['id']) {
    $xml = simplexml_load_file($gen['path']."\\configuration.xml");
    $xml->theme = $_GET['id'];
    $xml->asXML($gen['path']."\\configuration.xml");
    $host = "localhost";
    $port = $gen['port'];
    $pass = $gen['pass'];

    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    $result = socket_connect($socket, $host, $port);

    $login = "PASS\t$pass\tMeedioClientTester.exe\t\n\n\n";
    socket_write($socket, $login, strlen($login));

    $send = "MSG\tsystem.reboot\t\t0\t0\t\t0\t\t0\n\n\n".
            "QUIT\t\n\n\n";
    socket_write($socket, $send, strlen($send));
    socket_close($socket);
  }
  header("Location: $HTTP_REFERER");
  exit();
}

if ($_GET['what'] == "refresh") {
  $library = $_GET['library'];
  if (!$library) exit();

  $host = "localhost";
  $port = $gen['port'];
  $pass = $gen['pass'];

  $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  $result = socket_connect($socket, $host, $port);

  $login = "PASS\t$pass\tMeedioClientTester.exe\t\n\n\n";
  socket_write($socket, $login, strlen($login));

  $send = "MSG\tmeedio-helper.command.run-import\t\t0\t0\t\t1\tlibrary\t$library\t0\n\n\n".
          "QUIT\t\n\n\n";
  socket_write($socket, $send, strlen($send));
  socket_close($socket);

  header("Location: index.php?section=importers");
  exit();
}

if ($_GET['what'] == "command") {
  $cmd = $_GET['cmd'];
  $host = "localhost";
  $port = $gen['port'];
  $pass = $gen['pass'];

  $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  $result = socket_connect($socket, $host, $port);

  $login = "PASS\t$pass\tMeedioClientTester.exe\t\n\n\n";
  socket_write($socket, $login, strlen($login));

  $send = "MSG\tcommand\t\t0\t0\t\t1\tcommand\t$cmd\t0\n\n\n".
          "QUIT\t\n\n\n";
  socket_write($socket, $send, strlen($send));
  socket_close($socket);

  echo $close;
  exit();
}

if ($_GET['what'] == "message") {
  $msg = $_POST['msg'];
  if (!$msg) $msg = $_GET['msg'];
  $p = stripslashes($_POST['p']);
  $c = substr_count($p, "=");
  $p = str_replace("=", "\t", $p);
  $p = str_replace("\r\n", "\t", $p);

  $host = "localhost";
  $port = $gen['port'];
  $pass = $gen['pass'];

  $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  $result = socket_connect($socket, $host, $port);

  $login = "PASS\t$pass\tMeedioClientTester.exe\t\n\n\n";
  socket_write($socket, $login, strlen($login));

  $send = "MSG\t$msg\t\t0\t0\t\t$c\t$p\t0\n\n\n".
          "QUIT\t\n\n\n";
  socket_write($socket, $send, strlen($send));
  socket_close($socket);

  header("Location: $HTTP_REFERER");
  exit();
}

if ($_GET['what'] == "play") {

  $id = $_GET['id'];
  $library = $_GET['library'];
  $host = "localhost";
  $port = $gen['port'];
  $pass = $gen['pass'];

  $lib = sqlite_fetch_array(sqlite_query($config, "SELECT * FROM library WHERE id='$library'"));
  $db = sqlite_open($gen['path'] . "\\library\\". $lib['file']);

  if ($_GET['type'] == "album") {

    $sql_tags = sqlite_query($db, "SELECT * FROM tags");
    while ($tags = sqlite_fetch_array($sql_tags)) {
      if ($tags['tag_name'] == "Genre")     $tag_genre = $tags['tag_col'];
      if ($tags['tag_name'] == "Album")     $tag_album = $tags['tag_col'];
      if ($tags['tag_name'] == "Artist")    $tag_artist = $tags['tag_col'];
      if ($tags['tag_name'] == "Track")     $tag_track = $tags['tag_col'];
    }

    $album = sqlite_fetch_array(sqlite_query($db, "SELECT $tag_album FROM items WHERE item_id='$id'"));
    $album = $album[$tag_album];
    $sql = sqlite_query($db, "SELECT * FROM items WHERE $tag_album='$album' ORDER BY abs($tag_track)");
    for ($i=1; $song = sqlite_fetch_array($sql); $i++) {

      $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
      $result = socket_connect($socket, $host, $port);

      $login = "PASS\t$pass\tMeedioClientTester.exe\t\n\n\n";
      socket_write($socket, $login, strlen($login));

      if (($i == 1) && ($_GET['action'] == "play")) $msg = "music.play-file";
      else $msg = "music.queue-file";
      $title = $song['item_name'];
      $artist = $song[$tag_artist];
      $image = $song['item_image'];
      $track = $song[$tag_track];
      $file = $song['item_location'];
      $album = $song[$tag_album];
      $p = "caption\t$title\tfile\t$file\timage\t$image\ttrack\t$track\talbum\t$album\tartist\t$artist";
      $send = "MSG\t$msg\t\t0\t0\t\t6\t$p\t0\n\n\n";
      socket_write($socket, $send, strlen($send));
      $quit = "QUIT\t\n\n\n";
      socket_write($socket, $quit, strlen($quit));
      socket_close($socket);
    }
  }

  if ($_GET['type'] == "music") {

    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    $result = socket_connect($socket, $host, $port);

    $login = "PASS\t$pass\tMeedioClientTester.exe\t\n\n\n";
    socket_write($socket, $login, strlen($login));

    $sql_tags = sqlite_query($db, "SELECT * FROM tags");
    while ($tags = sqlite_fetch_array($sql_tags)) {
      if ($tags['tag_name'] == "Genre")     $tag_genre = $tags['tag_col'];
      if ($tags['tag_name'] == "Album")     $tag_album = $tags['tag_col'];
      if ($tags['tag_name'] == "Artist")    $tag_artist = $tags['tag_col'];
      if ($tags['tag_name'] == "Track")     $tag_track = $tags['tag_col'];
    }

    $song = sqlite_fetch_array(sqlite_query($db, "SELECT * FROM items WHERE item_id='$id'"));

    $title = $song['item_name'];
    $artist = $song[$tag_artist];
    $image = $song['item_image'];
    $track = $song[$tag_track];
    $file = $song['item_location'];
    $album = $song[$tag_album];

    if ($_GET['action'] == "play") $msg = "music.play-file";
    else $msg = "music.queue-file";
    $p = "caption\t$title\tfile\t$file\timage\t$image\ttrack\t$track\talbum\t$album\tartist\t$artist";
    $send = "MSG\t$msg\t\t0\t0\t\t6\t$p\t0\n\n\n";
    socket_write($socket, $send, strlen($send));
    usleep(500000);
    $quit = "QUIT\t\n\n\n";
    socket_write($socket, $quit, strlen($quit));
    socket_close($socket);
  }

  if ($_GET['type'] == "artist") {
    $sql_tags = sqlite_query($db, "SELECT * FROM tags");
    while ($tags = sqlite_fetch_array($sql_tags)) {
      if ($tags['tag_name'] == "Genre")     $tag_genre = $tags['tag_col'];
      if ($tags['tag_name'] == "Album")     $tag_album = $tags['tag_col'];
      if ($tags['tag_name'] == "Artist")    $tag_artist = $tags['tag_col'];
      if ($tags['tag_name'] == "Track")     $tag_track = $tags['tag_col'];
    }

    $artist = sqlite_fetch_array(sqlite_query($db, "SELECT $tag_artist FROM items WHERE item_id='$id'"));
    $artist = $artist[$tag_artist];
    if ($_GET['sort'] == "Album") $sort = $tag_album;
    else $sort = "item_name";
    $sql = sqlite_query($db, "SELECT * FROM items WHERE $tag_artist='$artist' ORDER BY $sort ASC");
    for ($i=1; $song = sqlite_fetch_array($sql); $i++) {
      $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
      $result = socket_connect($socket, $host, $port);

      $login = "PASS\t$pass\tMeedioClientTester.exe\t\n\n\n";
      socket_write($socket, $login, strlen($login));

      if (($i == 1) && ($_GET['action'] == "play")) $msg = "music.play-file";
      else $msg = "music.queue-file";
      $title = $song['item_name'];
      $artist = $song[$tag_artist];
      $image = $song['item_image'];
      $track = $song[$tag_track];
      $file = $song['item_location'];
      $album = $song[$tag_album];
      $p = "caption\t$title\tfile\t$file\timage\t$image\ttrack\t$track\talbum\t$album\tartist\t$artist";
      $send = "MSG\t$msg\t\t0\t0\t\t6\t$p\t0\n\n\n";
      socket_write($socket, $send, strlen($send));
      $quit = "QUIT\t\n\n\n";
      socket_write($socket, $quit, strlen($quit));
      socket_close($socket);
    }
  }
  if ($_GET['type'] == "movie") {
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    $result = socket_connect($socket, $host, $port);

    $login = "PASS\t$pass\tMeedioClientTester.exe\t\n\n\n";
    socket_write($socket, $login, strlen($login));
    $data = sqlite_fetch_array(sqlite_query($db, "SELECT item_location FROM items WHERE item_id='$id'"));
    $filename = $data['item_location'];
    if (substr($filename,0,1) == "|") $filename = substr($filename,1,strlen($filename));
    if (substr($filename,-1,1) == "|") $filename = substr($filename,0,strlen($filename) - 1);
    $files = split("\|", $filename);
    $num = count($files);
    for ($i = 0; $i < $num; $i++) {
      if ($i == 0) $msg = "standard-action.video.play-file";
      else $msg = "video.add-to-queue";
      $file = $files[$i];
      $send = "MSG\t$msg\t\t0\t0\t\t1\tfile\t$file\t0\n\n\n";
      socket_write($socket, $send, strlen($send));
    }
    $quit = "QUIT\t\n\n\n";
    socket_write($socket, $quit, strlen($quit));
    socket_close($socket);
  }
  echo $close;
  exit();
}

if ($_GET['what'] == "taskkill") {
  $pid = $_GET['pid'];
  if (!$pid) exit();
  exec("taskkill /pid $pid /f");
  header("Location: index.php?section=system");
  exit();
}

if ($_GET['what'] == "run") {
  $id = $_GET['id'];
  if (!$id) exit();
  $tmp = sqlite_fetch_array(sqlite_query($config, "SELECT * FROM applications WHERE id='$id'"));
  $title = $tmp['name'];
  $path = $tmp['path'];
  $run = $tmp['startstring'];
  system("start \"$title\" /D\"$path\" \"$run\"");
  header("Location: index.php?section=system");
  exit();
}

if ($_GET['what'] == "updatemovie") {
  if ((!$_GET['id']) || (!$_GET['library'])) exit();
  $gen = @sqlite_fetch_array(@sqlite_query($config, "SELECT * FROM general"));

  $id = addslashes($_GET['id']);
  $library = addslashes($_GET['library']);

  if ($_GET['imdb'] == 1) {
    require ("imdb.class.php");
    $movie = new imdb ($HTTP_GET_VARS["mid"]);
    if (isset ($HTTP_GET_VARS["mid"])) {
      $movieid = $HTTP_GET_VARS["mid"];
      $movie->setid ($movieid);

      $under = addslashes($movie->tagline());

      $plots = $movie->plot();
      $plot = $plots[0];

      $title = $movie->title();

      $genres = $movie->genres();
      $genre = "|";
      for ($i = 0; $i < count($genres); $i++) {
        $genre .= $genres[$i]."|";
      }

      $runtime = $movie->runtime()." min";

      $directors = $movie->director();
      $director = $directors[0]["name"];

      $cast = $movie->cast();
      if (count($cast) > 10) $cnt = 10;
      else $cnt = count($cast);
      $actors = "|";
      for ($i = 0; $i < $cnt; $i++) {
        $actors .= $cast[$i]["name"]."|";
      }

      $produced = $movie->year();

      $ratings = $movie->mpaa();
      $rating = $ratings["USA"];

      $review = $movie->rating();

      $under = stripslashes($under);
      $plot = stripslashes($plot);
      $title = stripslashes($title);
      $genre = stripslashes($genre);
      $runtime = stripslashes($runtime);
      $director = stripslashes($director);
      $actors = stripslashes($actors);
      $produced = stripslashes($produced);
      $rating = stripslashes($rating);
      $review = stripslashes($review);
    }
    else exit();
  }

  else {
    $under = $_POST['under'];
    $plot = $_POST['plot'];
    $title = $_POST['title'];
    $genre = $_POST['genre'];
    $runtime = $_POST['runtime'];
    $director = $_POST['director'];
    $actors = $_POST['actors'];
    $produced = $_POST['produced'];
    $review = $_POST['review'];
    $rating = $_POST['rating'];
  }

  $lib = sqlite_fetch_array(sqlite_query($config, "SELECT * FROM library WHERE id='$library'"));
  $db = sqlite_open($gen['path'] . "\\library\\". $lib['file']);

  ## Get Tags (New in 0.2)

  $sql_tags = sqlite_query($db, "SELECT * FROM tags");

  while ($tags = sqlite_fetch_array($sql_tags)) {
    if ($tags['tag_name'] == "Genre")     $tag_genre = $tags['tag_col'];
    if ($tags['tag_name'] == "Runtime")   $tag_runtime = $tags['tag_col'];
    if ($tags['tag_name'] == "Actors")    $tag_actors = $tags['tag_col'];
    if ($tags['tag_name'] == "Director")  $tag_director = $tags['tag_col'];
    if ($tags['tag_name'] == "Directors") $tag_directors = $tags['tag_col'];
    if ($tags['tag_name'] == "Overview")  $tag_overview = $tags['tag_col'];
    if ($tags['tag_name'] == "Subtitle")  $tag_subtitle = $tags['tag_col'];
    if ($tags['tag_name'] == "Produced")  $tag_produced = $tags['tag_col'];
    if ($tags['tag_name'] == "Rating")    $tag_rating = $tags['tag_col'];
    if ($tags['tag_name'] == "Review")    $tag_review = $tags['tag_col'];

  }

  if (!$tag_genre) {
    $sql_chk = sqlite_query($db, "SELECT tag_col FROM tags WHERE tag_free='1'");
    if (sqlite_num_rows($sql_chk) < 1) {
      echo "There is a problem with your library file, you probably dont have an IMDB importer installed!";
      exit();
    }
    else {
      $chk = sqlite_fetch_array($sql_chk);
      $tag_genre = $chk['tag_col'];
      sqlite_query($db, "UPDATE tags SET tag_name='Genre',tag_free='0' WHERE tag_col='$tag_genre'");
    }
  }

  if (!$tag_runtime) {
    $sql_chk = sqlite_query($db, "SELECT tag_col FROM tags WHERE tag_free='1'");
    if (sqlite_num_rows($sql_chk) < 1) {
      echo "There is a problem with your library file, you probably dont have an IMDB importer installed!";
      exit();
    }
    else {
      $chk = sqlite_fetch_array($sql_chk);
      $tag_runtime = $chk['tag_col'];
      sqlite_query($db, "UPDATE tags SET tag_name='Runtime',tag_free='0' WHERE tag_col='$tag_runtime'");
    }
  }

  if (!$tag_actors) {
    $sql_chk = sqlite_query($db, "SELECT tag_col FROM tags WHERE tag_free='1'");
    if (sqlite_num_rows($sql_chk) < 1) {
      echo "There is a problem with your library file, you probably dont have an IMDB importer installed!";
      exit();
    }
    else {
      $chk = sqlite_fetch_array($sql_chk);
      $tag_actors = $chk['tag_col'];
      sqlite_query($db, "UPDATE tags SET tag_name='Actors',tag_free='0' WHERE tag_col='$tag_actors'");
    }
  }

  if ((!$tag_directors) && ($tag_director)) $tag_directors = $tag_director;
  if ((!$tag_director) && (!$tag_directors)) {
    $sql_chk = sqlite_query($db, "SELECT tag_col FROM tags WHERE tag_free='1'");
    if (sqlite_num_rows($sql_chk) < 1) {
      echo "There is a problem with your library file, you probably dont have an IMDB importer installed!";
      exit();
    }
    else {
      $chk = sqlite_fetch_array($sql_chk);
      $tag_directors = $chk['tag_col'];
      sqlite_query($db, "UPDATE tags SET tag_name='Director',tag_free='0' WHERE tag_col='$tag_director'");
    }
  }

  if (!$tag_overview) {
    $sql_chk = sqlite_query($db, "SELECT tag_col FROM tags WHERE tag_free='1'");
    if (sqlite_num_rows($sql_chk) < 1) {
      echo "There is a problem with your library file, you probably dont have an IMDB importer installed!";
      exit();
    }
    else {
      $chk = sqlite_fetch_array($sql_chk);
      $tag_overview = $chk['tag_col'];
      sqlite_query($db, "UPDATE tags SET tag_name='Overview',tag_free='0' WHERE tag_col='$tag_overview'");
    }
  }

  if (!$tag_subtitle) {
    $sql_chk = sqlite_query($db, "SELECT tag_col FROM tags WHERE tag_free='1'");
    if (sqlite_num_rows($sql_chk) < 1) {
      echo "There is a problem with your library file, you probably dont have an IMDB importer installed!";
      exit();
    }
    else {
      $chk = sqlite_fetch_array($sql_chk);
      $tag_subtitle = $chk['tag_col'];
      sqlite_query($db, "UPDATE tags SET tag_name='Subtitle',tag_free='0' WHERE tag_col='$tag_subtitle'");
    }
  }

  if (!$tag_produced) {
    $sql_chk = sqlite_query($db, "SELECT tag_col FROM tags WHERE tag_free='1'");
    if (sqlite_num_rows($sql_chk) < 1) {
      echo "There is a problem with your library file, you probably dont have an IMDB importer installed!";
      exit();
    }
    else {
      $chk = sqlite_fetch_array($sql_chk);
      $tag_produced = $chk['tag_col'];
      sqlite_query($db, "UPDATE tags SET tag_name='Produced',tag_free='0' WHERE tag_col='$tag_produced'");
    }
  }

  if (!$tag_rating) {
    $sql_chk = sqlite_query($db, "SELECT tag_col FROM tags WHERE tag_free='1'");
    if (sqlite_num_rows($sql_chk) < 1) {
      echo "There is a problem with your library file, you probably dont have an IMDB importer installed!";
      exit();
    }
    else {
      $chk = sqlite_fetch_array($sql_chk);
      $tag_rating = $chk['tag_col'];
      sqlite_query($db, "UPDATE tags SET tag_name='Rating',tag_free='0' WHERE tag_col='$tag_rating'");
    }
  }

  if (!$tag_review) {
    $sql_chk = sqlite_query($db, "SELECT tag_col FROM tags WHERE tag_free='1'");
    if (sqlite_num_rows($sql_chk) < 1) {
      echo "There is a problem with your library file, you probably dont have an IMDB importer installed!";
      exit();
    }
    else {
      $chk = sqlite_fetch_array($sql_chk);
      $tag_review = $chk['tag_col'];
      sqlite_query($db, "UPDATE tags SET tag_name='Review',tag_free='0' WHERE tag_col='$tag_review'");
    }
  }

  $create_trigger =     "create trigger item_dates_update after update on items
                        begin
                            update item_dates set modified = idt_now()
                                where item_id = '$id';
                            update parameters set param_value = param_value + 1
                                where param_name = \"data-version\";
                        end";

  $drop = sqlite_query($db, "drop trigger item_dates_update");
  $update = sqlite_query($db, "UPDATE items SET
                                                item_name=\"$title\",
                                                $tag_subtitle=\"$under\",
                                                $tag_overview=\"$plot\",
                                                $tag_genre=\"$genre\",
                                                $tag_runtime=\"$runtime\",
                                                $tag_directors=\"$director\",
                                                $tag_actors=\"$actors\",
                                                $tag_produced=\"$produced\",
                                                $tag_rating=\"$rating\",
                                                $tag_review=\"$review\"
                                                WHERE item_id=\"$id\"");
  $create = sqlite_query($db, $create_trigger);

  header("Location: index.php?section=library&library=$library&id=$id");
}



if ($_GET['what'] == "updatesong") {
  if (!$_GET['id']) exit();
  $gen = @sqlite_fetch_array(@sqlite_query($config, "SELECT * FROM general"));
  $id = addslashes($_GET['id']);
  $library = $_GET['library'];

  $title = addslashes($_POST['title']);
  $artist = addslashes($_POST['artist']);
  $album = addslashes($_POST['album']);
  $track = addslashes($_POST['track']);

  $lib = sqlite_fetch_array(sqlite_query($config, "SELECT * FROM library WHERE id='$library'"));
  $db = sqlite_open($gen['path'] . "\\library\\". $lib['file']);

  ## Get Tags (New in 0.2)

  $sql_tags = sqlite_query($db, "SELECT * FROM tags");

  while ($tags = sqlite_fetch_array($sql_tags)) {
    if ($tags['tag_name'] == "Genre")     $tag_genre = $tags['tag_col'];
    if ($tags['tag_name'] == "Album")     $tag_album = $tags['tag_col'];
    if ($tags['tag_name'] == "Artist")    $tag_artist = $tags['tag_col'];
    if ($tags['tag_name'] == "Track")     $tag_track = $tags['tag_col'];
  }


  $create_trigger =     "create trigger item_dates_update after update on items
                        begin
                            update item_dates set modified = idt_now()
                                where item_id = '$id';
                            update parameters set param_value = param_value + 1
                                where param_name = \"data-version\";
                        end";

  $drop = sqlite_query($db, "drop trigger item_dates_update");
  $update = sqlite_query($db, "UPDATE items SET item_name='$title', $tag_album='$album', $tag_artist=\"$artist\", $tag_track='$track' WHERE item_id='$id'");
  $create = sqlite_query($db, $create_trigger);
  if ($_GET['from'] == "artist") {
    header("Location: index.php?section=library&library=$library&artist=$id");
    exit();
  }
  else {
    header("Location: index.php?section=library&library=$library&album=$id");
    exit();
  }
}

/**
* Changes a tag value in a library
*   - what=update-tag
*   - id: item id
*   - library: library name
*   - tag: tag field
*   - value: new value
**/
if ( $_GET['what'] == 'update-tag' )
{
    if ( !$_GET['id'] ) exit( "Missing parameter 'id'" );
    $id = $_GET['id'];

    if ( !$_GET['library'] ) exit( "Missing parameter 'library'" );
    $library = $_GET['library'];

    if ( !$_GET['tag'] ) exit( "Missing parameter 'tag'" );
    $tag = $_GET['tag'];

    if ( !isset( $_GET['value'] ) ) exit( "Missing parameter 'value'" );
    $value = $_GET['value'];

    // ouverture librairie
    try
    {
        weebUIMovieListFunctions::runUpdateLibraryQuery( $library, "UPDATE items SET $tag='$value' WHERE item_id='$id'" );
    }
    catch ( Exception $e )
    {
        echo get_class( $e ) . ": " . $e->getMessage();
        return false;
    }

    header( 'Location: ' . $HTTP_REFERER );
    exit;
}

/**
* Movie archiving
*   - what=archive-movie
*   - id: movie id
*   - to-volume: name of the new disk volume
*   - from-volume: name of the current disk volume
*   - library: library name
*   - location: current item location (path)
*   - item-ext-id: current item ext id
**/
if ( $_GET['what'] == 'archive-movie' )
{
    if ( !isset( $_GET[ 'id'] ) ) exit('Missing parameter \'id\'');
    $id = $_GET['id'];

    if ( !isset( $_GET[ 'from-volume'] ) ) exit( "Missing parameter 'from-volume'" );
    $fromVolume = $_GET['from-volume'];

    if ( !isset( $_GET[ 'to-volume'] ) ) exit( "Missing parameter 'to-volume'" );
    $toVolume = $_GET['to-volume'];

    if ( !isset( $_GET['library'] ) ) exit( "Missing parameter 'library'" );
    $library = $_GET['library'];

    if ( !isset( $_GET['location'] ) ) exit( "Missing parameter 'location'" );
    $location = $_GET['location'];

    if ( !isset( $_GET['tag-name'] ) ) exit( "Missing parameter 'tag-name'" );
    $tagName = $_GET['tag-name'];

    if ( !isset( $_GET['item-ext-id'] ) ) exit( "Missing parameter 'item-ext-id'" );
    $itemExtID = $_GET['item-ext-id'];

    $fromVolume = weebUIVolumeManager::loadVolume( $library, $fromVolume );
    $toVolume = weebUIVolumeManager::loadVolume( $library, $toVolume );
    $newLocation = str_replace( $fromVolume->path, $toVolume->path, $location );
    $newItemExtID = str_replace( strtolower( $fromVolume->path ), strtolower( $toVolume->path ), $itemExtID );

    $sql = "UPDATE items SET $tagName = '" . sqlite_escape_string( $toVolume->name ) . "', " .
           "                 item_location = '" . sqlite_escape_string( $newLocation ) . "', ".
           "                 item_ext_id = '" . sqlite_escape_string( $newItemExtID ) . "' " .
           "WHERE item_id = $id";
    try {
        weebUIMovieListFunctions::runUpdateLibraryQuery( $library, $sql );
        header( 'Location: ' . $HTTP_REFERER );
    } catch ( Exception $e ) {
        echo get_class( $e ) . ': ' . $e->getMessage();
        exit;
    }
}

/**
* Change image action
*   - what: change-image
*   - id: item-id
*   - library: library ID
*   - image: new image file
**/
if ( $_POST['what'] == 'change-image' )
{
    if ( !isset( $_POST[ 'id'] ) ) exit('Missing parameter \'id\'' );
    $id = $_POST['id'];

    if ( !isset( $_POST['library'] ) ) exit( "Missing parameter 'library'" );
    $library = $_POST['library'];

    if ( !isset( $_POST['movie-title'] ) ) exit( "Missing parameter 'movie-title'" );
    $movieTitle = $_POST['movie-title'];

    if ( !isset( $_FILES['image'] ) ) exit( "Missing parameter 'image'" );
    $extension = pathinfo( $_FILES['image']['name'], PATHINFO_EXTENSION );
    $targetName = preg_replace( '/[^a-z0-9]/', '', strtolower( $movieTitle ) );
    $filePath = 'C:\\Meedio\\MeedioData\\Cache\\Nicecovers Stills\\' . $targetName . '.' . $extension;

    $sql = "UPDATE items SET item_image = '" . sqlite_escape_string( $filePath ) . "' " .
           "WHERE item_id = $id";
    if ( !move_uploaded_file( $_FILES['image']['tmp_name'], $filePath ) )
    {
        exit( "An error occured moving the image to $filePath" );
    }
    else
    {
        try {
            weebUIMovieListFunctions::runUpdateLibraryQuery( $library, $sql );
            header( 'Location: ' . $HTTP_REFERER );
        } catch ( Exception $e ) {
            echo get_class( $e ) . ': ' . $e->getMessage();
            exit;
        }
    }
}
?>